package com.sc.general.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sc.general.dao.FileMapper;
import com.sc.general.dto.FileQueryDTO;
import com.sc.general.entity.ProjectFile;
import com.sc.general.service.FileService;
import com.sc.general.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * 文件服务impl
 *
 * @author 徐赫阳
 * @date 2021/11/11
 */
@Service
@Component
public class FileServiceImpl extends ServiceImpl<FileMapper, ProjectFile> implements FileService {


    /**
     * 文件映射器
     */
    @Autowired
    private FileMapper fileMapper;

    @Override
    public PageVO<ProjectFile> getFileList(FileQueryDTO queryDTO){

        QueryWrapper<ProjectFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .like(queryDTO.getName() != null,ProjectFile::getName,queryDTO.getName())
                .orderByDesc(ProjectFile::getId);
        Integer count = this.fileMapper.selectList(queryWrapper).size();
        List<ProjectFile> list = this.fileMapper.selectList(queryWrapper.lambda().last("LIMIT "+ (queryDTO.getPage() - 1) * queryDTO.getPageSize() + ","+ queryDTO.getPageSize()));
        return PageVO.setPage(queryDTO.getPage(),queryDTO.getPageSize(),list,count);
    }

    @Override
    public void deleteById(Integer id){
        ProjectFile projectFile = this.fileMapper.selectById(id);
        if(projectFile != null){
            File file = new File(projectFile.getRealPath());
            if(file.exists()){
                file.delete();
            }
        }
        this.fileMapper.deleteById(id);
    }


}
